package com.ashin.leetcode;

import org.junit.Test;

public class L008Atoi {

    @Test
    public void test() {
        System.out.println(myAtoi("-123 xx"));
    }

    public int myAtoi(String s) {
        String trim = s.trim();

        int flag = 1;
        char firstChar = trim.charAt(0);
        if (firstChar == '-' || firstChar == '+') {
            if (firstChar == '-') {
                flag = -1;
            }

            trim = trim.substring(1);
        }

        StringBuilder numStr = new StringBuilder();
        for (char c : trim.toCharArray()) {
            if (c >= '0' && c <= '9') {
                numStr.append(c);
            } else {
                break;
            }
        }

        int r = 0;
        int unit = 0;
        for (int i = numStr.length() - 1; i >= 0; i--) {
            int num = numStr.charAt(i) - 48;
            r += num * Math.pow(10, unit++);
        }


        return r * flag;
    }
}
